#!/bin/bash
#
# Copyright 2015 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# This script replaces the default initctl script provided by upstart.
#
# Since docker does not support upstart, the default initctl script actually
# does nothing. In order for easy managment of umpire server, we provide a
# this script so we can still use `start/stop/restart umpire` to manage umpire
# service.

INSTALL_DIR=/var/db/factory/umpire
TOOLKIT_DIR=toolkits/server/active
UMPIRED=usr/local/factory/bin/umpired

start_umpire() {
  nohup $INSTALL_DIR/$1/$TOOLKIT_DIR/$UMPIRED >/dev/null </dev/null 2>&1 &
  local pid="$(pgrep -f $INSTALL_DIR/$1/$TOOLKIT_DIR/$UMPIRED)"
  echo "umpire start/running, process $pid"
}

stop_umpire() {
  pkill -f "$INSTALL_DIR/$1/$TOOLKIT_DIR/$UMPIRED"
  echo "umpire stop/waiting"
}

status_umpire() {
  local pid="$(pgrep -f $INSTALL_DIR/$1/$TOOLKIT_DIR/$UMPIRED)"
  if [ -z "$pid" ]; then
    echo "umpire stop/waiting"
  else
    echo "umpire start/running, process $pid"
  fi
}

main() {
  local cmd="${1##*/}"
  local service_name="$2"

  if [ "${cmd}" == "initctl" ]; then
    cmd="$2"
    service_name="$3"
    shift 3
  else
    shift 2
  fi

  # Evaluate the rest of the argument as environment variables
  # For example: BOARD=samus
  while [ "$#" -gt 0 ]; do
    if [ -n "echo $1 | grep '='" ]; then
      eval "$1"
    fi
    shift
  done

  if [ -z "$BOARD" ]; then
    echo "ERROR: BOARD not specified"
    exit 1
  fi

  if [ "${service_name}" == "umpire" ]; then
    case "${cmd}" in
      start)
        start_umpire $BOARD
        ;;
      stop)
        stop_umpire $BOARD
        ;;
      restart)
        stop_umpire $BOARD
        sleep 1
        start_umpire $BOARD
        ;;
      status)
        status_umpire $BOARD
    esac
  fi
}

main $0 $@
exit 0
